package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.PageParam;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RequestMapping("/dish")
@RestController
public class DishController {
    
    @Autowired
    private DishService ds;

    
    //根据分类的id，获取菜品数据
    @GetMapping("/list")
    public R list(long categoryId , Integer status){
    
        try {
            //1. 调用service
            List<DishDto> list = ds.findByCategoryId(categoryId , status);
        
            return R.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("查询失败！");
        }
    
    }
    
    //更新菜品
    @PutMapping
    public R update(@RequestBody DishDto dishDto){
        
        int row = ds.update(dishDto);
        if(row >0 ){
            return R.success("更新成功!");
        }else{
            return R.error("更新失败！");
        }
    
    }
    
    //分页查询菜品
    @GetMapping("/page")
    public R findPage(PageParam pageParam){
    
        try {
            //1. 调用service
            IPage<DishDto> page = ds.findPage(pageParam);
        
            //2. 返回数据
            return R.success(page);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("分页查询失败！");
        }
    }

    //添加菜品
    @PostMapping
    public R add(@RequestBody DishDto dishDto){
    
        //1. 调用service
        int row = ds.add(dishDto);
    
        //2. 返回
        if(row >0 ){
            return R.success("添加菜品成功！");
        }else{
            return R.error("添加菜品失败！");
        }
    
    }

    //修改菜品状态
    @PostMapping("/status")
    public R updateStatus(@RequestBody Dish dish, Long dishId) {

        //调用service
        int rows = ds.updateStatus(dish,dish.getId());

        if (rows > 0) {
            return R.success("修改状态成功！");
        } else {
            return R.error("修改状态失败！");
        }
    }

    //批量/删除菜品数据
    @DeleteMapping
    public R delete(@RequestParam List<Long> ids) {
        //调用service
        int rows = ds.delete(ids);
        if (rows > 0) {
            return R.success("删除菜品数据成功！");
        } else {
            return R.error("删除菜品数据失败！");
        }
    }
}
